using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Threading;

using Stunt.Nutss.Stunt;
using Stunt.Nutss.Signaling;
using Stunt.Nutss;

namespace SigServer
{

	internal class Startup
	{

		static readonly int PROXY_PORT = 51641;

		/// <summary>Starts the Signaling Server</summary>
		/// <param name="args">Program arguments</param>
		[STAThread]
		public static void Main(string[] args)
		{
			STUNTServer r1, r2;
			SlingServer p;

			if (args.Length != 2)
			{
				Usage();
			}

			try
			{
				//testing purposes only feel free to remove this anytime
				//IPHostEntry ipe = Dns.GetHostEntry("localhost");
				//IPAddress addr1 = ipe.AddressList[0];
				//IPAddress addr2 = addr1;

				IPAddress addr1 = IPAddress.Parse(args[0]);
				IPAddress addr2 = IPAddress.Parse(args[1]);

				r1 = new STUNTServer(addr1, PROXY_PORT + 16 + (int)(10 * new Random().NextDouble()));
				r2 = new STUNTServer(addr2, PROXY_PORT + 32 + (int)(10 * new Random().NextDouble()));

				EndPoint[] addrs = new EndPoint[] { r1.GetSocketAddress(), r2.GetSocketAddress() };
				p = new SlingServer(PROXY_PORT, addrs);

				Console.WriteLine("STUNT Server 1: {0}", r1.GetSocketAddress());
				Console.WriteLine("STUNT Server 2: {0}", r2.GetSocketAddress());
				Console.WriteLine("Directory  : {0}", p.EndPoint);

				new Thread(new ThreadStart(r1.ThreadProcess)).Start();
				new Thread(new ThreadStart(r2.ThreadProcess)).Start();
				new Thread(new ThreadStart(p.ThreadProcess)).Start();
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}


		private static void Usage()
		{
			Console.WriteLine("Usage:\n\t SigServer ip1 ip2\n" + "The two IP Addresses should be different and belong to local interfaces.\n");
			System.Environment.Exit(1);
		}
	}
}